package com.jimmyhsu.ecnudaowei.coursetable.edit;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import com.jimmyhsu.ecnudaowei.Bean.TaskActivity;
import com.jimmyhsu.ecnudaowei.Db.UserDbHelper;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.coursetable.ChooseWeekActivity;
import com.jimmyhsu.ecnudaowei.coursetable.CourseTableFragment;
import com.jimmyhsu.ecnudaowei.coursetable.view.CourseTableCondensedLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddOrEditCourseActivity extends AppCompatActivity {

    private static final String TAG = "AddOrEditCourseActivity";
    public static final String ACTION_COURSE_REFRESH = "action_course_refresh";
    private static final String EXTRA_START = "extra_start";
    private static final String EXTRA_END = "extra_end";
    private static final String EXTRA_DAY = "extra_day";
    private static final String EXTRA_LOC = "extra_loc";
    private static final String EXTRA_COURSE_NAME = "extra_course_name";
    private static final String EXTRA_TEACHER = "extra_teacher";
    private static final String EXTRA_WEEK = "extra_week";
    private static final String EXTRA_WEEK_SEL = "extra_week_sel";
    private static final String EXTRA_MAX_WEEK = "extra_max_week";
    private static final String EXTRA_COURSE_ID = "extra_course_id";
    private static final String EXTRA_ADDED_BY_USER = "extra_added_by_user";
    private static final String EXTRA__ID = "extra__id";

    public static final int REQUEST_COURSE_ADD = 1;
    public static final String KEY_WEEK = "key_week";
    private static final int REQUEST_WEEK = 0;

    private int mStart;
    private int mEnd;
    private int mDay;
    private int _id = -1;

    private String courseName;
    private String teacher;
    private String location;
    private String courseWeek;
    private String courseId;

    private int maxWeek;
    private boolean isNewCourse = true;
    private boolean isAddedByUser = true;

    private List<String> mWeekDatas;

    @BindView(R.id.id_aoe_condensed)
    CourseTableCondensedLayout mCourseTableCondensed;
    @BindView(R.id.id_aoe_begin_time)
    TextView mTvBeginTime;
    @BindView(R.id.id_aoe_end_time)
    TextView mTvEndTime;
    @BindView(R.id.id_aoe_week)
    TextView mTvWeek;
    @BindView(R.id.id_aoe_course_name)
    EditText mEdtCourseName;
    @BindView(R.id.id_aoe_loc)
    EditText mEdtLocation;
    @BindView(R.id.id_aoe_teacher)
    EditText mEdtTeacher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_or_edit_course);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ButterKnife.bind(this);
        initCourseTable();
        initWeekData();
        initTimeData();
        initOtherData();
        mEdtLocation.setEnabled(isAddedByUser);
    }

    private void initOtherData() {
        teacher = getIntent().getStringExtra(EXTRA_TEACHER);
        courseName = getIntent().getStringExtra(EXTRA_COURSE_NAME);
        location = getIntent().getStringExtra(EXTRA_LOC);
        courseId = getIntent().getStringExtra(EXTRA_COURSE_ID);
        isAddedByUser = getIntent().getBooleanExtra(EXTRA_ADDED_BY_USER, true);
        _id = getIntent().getIntExtra(EXTRA__ID, -1);
        if (teacher != null) {
            mEdtTeacher.setText(teacher);
        }
        if (courseName != null) {
            mEdtCourseName.setText(courseName);
            isNewCourse = false;
        }
        if (location != null) {
            mEdtLocation.setText(location);
        }
    }

    private void initTimeData() {
        String startTime = CourseTableFragment.COURSE_TIME_START_POINT[mStart];
        String endTime = CourseTableFragment.COURSE_TIME_END_POINT[mEnd];
        mTvBeginTime.setText(startTime);
        mTvEndTime.setText(endTime);
    }

    private void initWeekData() {
        mWeekDatas = getIntent().getBundleExtra(EXTRA_WEEK).getStringArrayList(KEY_WEEK);
        courseWeek = getIntent().getStringExtra(EXTRA_WEEK_SEL);
        maxWeek = getIntent().getIntExtra(EXTRA_MAX_WEEK, 20);
    }

    private void initCourseTable() {
        mStart = getIntent().getIntExtra(EXTRA_START, 0);
        mEnd = getIntent().getIntExtra(EXTRA_END, 0);
        mDay = getIntent().getIntExtra(EXTRA_DAY, 0);
        mCourseTableCondensed.setPeriod(mDay, mStart, mEnd);
    }

    @OnClick(R.id.id_aoe_save)
    void save() {
        courseName = mEdtCourseName.getText().toString();
        teacher = mEdtTeacher.getText().toString();
        location = mEdtLocation.getText().toString();
        if ("".equals(courseName) || "".equals(teacher) || "".equals(location) || courseWeek == null) {
            Snackbar.make(mEdtLocation, "请填写必要信息", Snackbar.LENGTH_SHORT).show();
            return;
        }
        UserDbHelper dbHelper = UserDbHelper.getInstance(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(TaskActivity.COL_DURATION, mEnd - mStart + 1);
        values.put(TaskActivity.COL_NUMBER, mStart);
        values.put(TaskActivity.COL_DAY, mDay);
        values.put(TaskActivity.COL_TEACHER, teacher);
        values.put(TaskActivity.COL_COURSE_WEEK, courseWeek);
        values.put(TaskActivity.COL_COURSE_NAME, courseName);
        if (isNewCourse) {
            values.put(TaskActivity.COL_LOCATION, location);
            values.put(TaskActivity.COL_ADD_BY_USER, 1);
            values.put(TaskActivity.COL_COURSE_ID, "");
            db.insert(TaskActivity.TB_COURSE, null, values);
        } else {
            if (isAddedByUser) {
                values.put(TaskActivity.COL_LOCATION, location);
                values.put(TaskActivity.COL_ADD_BY_USER, 1);
                values.put(TaskActivity.COL_COURSE_ID, "");
            }
            db.update(TaskActivity.TB_COURSE,
                    values,
                    "_id="+_id,
                    null);
        }
        db.close();
        setResult(RESULT_OK);
        sendBroadcast(new Intent(ACTION_COURSE_REFRESH));
        finish();
    }

    @OnClick(R.id.id_aoe_week)
    void chooseWeek() {
        String[] weekArr = new String[mWeekDatas.size()];
        ChooseWeekActivity.startActivityForResult(REQUEST_WEEK, this, mWeekDatas.toArray(weekArr));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_WEEK:
                    Bundle bundle = data.getBundleExtra(ChooseWeekActivity.EXTRA_DATA);
                    ArrayList<Integer> selectedWeekIndex = bundle
                            .getIntegerArrayList(ChooseWeekActivity.BUNDLE_KEY_SELECTED_LIST);
                    StringBuilder sb = new StringBuilder();
                    sb.append('0');
                    if (selectedWeekIndex != null) {
                        for (int i = 1; i <= maxWeek; i++) {
                            if (selectedWeekIndex.contains((i - 1))) {
                                sb.append('1');
                            } else {
                                sb.append('0');
                            }
                        }
                    }
                    courseWeek = sb.toString();
                    mTvWeek.setText(CourseTableFragment.parseWeek(courseWeek));
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static void startActivity(Context context, int _id, int day, int start, int end,
                                     List<String> weekDatas, int maxWeek, String location,
                                     String teacher, String weekSelected, String courseName,
                                     String courseId, boolean addedByUser) {
        Intent intent = new Intent(context, AddOrEditCourseActivity.class);
        intent.putExtra(EXTRA__ID, _id);
        intent.putExtra(EXTRA_START, start);
        intent.putExtra(EXTRA_END, end);
        intent.putExtra(EXTRA_DAY, day);
        intent.putExtra(EXTRA_MAX_WEEK, maxWeek);
        intent.putExtra(EXTRA_LOC, location);
        intent.putExtra(EXTRA_TEACHER, teacher);
        intent.putExtra(EXTRA_WEEK_SEL, weekSelected);
        intent.putExtra(EXTRA_COURSE_NAME, courseName);
        intent.putExtra(EXTRA_COURSE_ID, courseId);
        intent.putExtra(EXTRA_ADDED_BY_USER, addedByUser);
        Bundle bundle = new Bundle();
        bundle.putStringArrayList(KEY_WEEK, (ArrayList<String>) weekDatas);
        intent.putExtra(EXTRA_WEEK, bundle);
        ((Activity)context).startActivityForResult(intent, REQUEST_COURSE_ADD);
    }

    public static void startActivity(Context context, int day, int start, int end,
                                     List<String> weekDatas, int maxWeek) {
        Intent intent = new Intent(context, AddOrEditCourseActivity.class);
        intent.putExtra(EXTRA_START, start);
        intent.putExtra(EXTRA_END, end);
        intent.putExtra(EXTRA_DAY, day);
        intent.putExtra(EXTRA_MAX_WEEK, maxWeek);
        Bundle bundle = new Bundle();
        bundle.putStringArrayList(KEY_WEEK, (ArrayList<String>) weekDatas);
        intent.putExtra(EXTRA_WEEK, bundle);
        ((Activity)context).startActivityForResult(intent, REQUEST_COURSE_ADD);
    }
}
